package cn.bocweb.spinning.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CollectRemoveBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.TestCollectBean;
import cn.bocweb.spinning.model.Bean.TrainRandomStartBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.adapter.TrainAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.dialog.ExerciseFinishDialog;
import cn.bocweb.spinning.view.fragment.TrainFragment;
import de.greenrobot.event.EventBus;

public class TrainActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.test_btn_test_list)
    LinearLayout testBtnTestList;
    @Bind(R.id.time_limited)
    TextView timeLimited;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.link_exam_fragment)
    ViewPager linkExamFragment;

    int answerWrong = 0, right, wrong, miss;
    boolean collected;

    TextView examPopupRight;
    TextView examPopupWrong;
    TextView examPopupMiss;
    TrainAdapter adapter;
    TestListAdapter testListAdapter;
    PopupWindow popupWindow;
    Map<Integer, Boolean> list;
    RelativeLayout iv;

    @Bind(R.id.train_quiz_num)
    TextView trainQuizNum;
    @Bind(R.id.train_quiz_count)
    TextView trainQuizCount;

    List<TrainFragment> fragments;
    UserPresenter presenter;
    UserBean.DataEntity dataEntity;
    int size, position, trainType, popupwindowClickPosition = 0, total;
    String userid, libId;
    boolean isClientSelect = false, isPopupWindowClick = false;
    ExerciseFinishDialog finishDialog;

    @Bind(R.id.train_check_detail)
    LinearLayout trainCheckDetail;
    @Bind(R.id.train_collect)
    LinearLayout trainCollect;

    Map<Integer, String> trainId;
    Map<Integer, String> trainTtype;
    Map<Integer, Integer> trainChoose;
    @Bind(R.id.imageview_collect)
    ImageView imageviewCollect;
    @Bind(R.id.linearLayout_empty)
    LinearLayout linearLayoutEmpty;
    @Bind(R.id.prev_quiz)
    LinearLayout prev_quiz;
    @Bind(R.id.next_quiz)
    LinearLayout next_quiz;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train);
        ButterKnife.bind(this);

        trainId = new HashMap<>();
        trainTtype = new HashMap<>();
        trainChoose = new HashMap<>();
        dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();

        fragments = new ArrayList<>();

        finishDialog = new ExerciseFinishDialog(this);
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        libId = lib.getId();
        EventBus.getDefault().register(this);

        initViewPager();
        initToolbar();
        initPopupWindow();
        initClickBtn();
        initIntent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (userid == null || userid.isEmpty()) {
            UserBean.DataEntity dataEntity = new UserBean.DataEntity();
            dataEntity.readInfoFromLocal(this);
            userid = dataEntity.getUserid();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.TRAIN_TO_LOGIN: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                break;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initIntent() {

        presenter = new UserPresenterImp();
        Intent intent = getIntent();
        trainType = intent.getIntExtra(Constant.TRAIN, 0);
        showLoading();
        switch (trainType) {
            case Constant.TRAIN_RANDOM: {
                presenter.trainRandomStart("1", libId, userid, "1");
                break;
            }
            case Constant.TRAIN_ERROR: {
                presenter.errorTrainStart("1", libId, userid);
                break;
            }
            case Constant.TRAIN_DIFF: {
                presenter.hardTrainStart("1", libId, userid);
                break;
            }
        }
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finishDialog.setOnClickListener(new ExerciseFinishDialog.OnClickListener() {
                    @Override
                    public void click(View v) {
                        dialog.dismiss();
                        finish();
                    }
                });
                finishDialog.show();
//                AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
//                builder.setTitle("温馨提示");
//                builder.setMessage("是否退出答题");
//                builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        finish();
//
//                    }
//                });
//                builder.show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否退出答题");
        builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();

            }
        });
        builder.show();
    }

    private void initPopupWindow() {

        list = new HashMap<>();
        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        GridView gridView_testList = (GridView) view.findViewById(R.id.test_list);
        iv = (RelativeLayout) view.findViewById(R.id.btn_hide);

        testListAdapter = new TestListAdapter(this, size, list, false);

        examPopupRight = (TextView) view.findViewById(R.id.exam_popup_right);
        examPopupWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        examPopupMiss = (TextView) view.findViewById(R.id.exam_popup_miss);

        gridView_testList.setAdapter(testListAdapter);


        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        int toolbarHeight = DeviceUtil.getViewHeight(toolbar);

        /**
         * 安卓5.0以下有个问题就是用gridview的onItemClickListener监听不到item的监听事件.真他妈的奇怪
         */
        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {
            @Override
            public void click(int position) {
                isPopupWindowClick = true;
                popupwindowClickPosition = position;
                linkExamFragment.setCurrentItem(position);
                popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, screenHeightPx - navigationHeight - toolbarHeight);
        popupWindow.setAnimationStyle(R.style.test_list);

    }

    private void initClickBtn() {
        testBtnTestList.setOnClickListener(this);
        iv.setOnClickListener(this);
        trainCheckDetail.setOnClickListener(this);
        trainCollect.setOnClickListener(this);
        prev_quiz.setOnClickListener(this);
        next_quiz.setOnClickListener(this);
    }

    private void initViewPager() {
//        adapter = new TrainAdapter(getSupportFragmentManager(), fragments);
        linkExamFragment.setAdapter(adapter);
        linkExamFragment.setPageTransformer(true, new ZoomOutPageTransformer());
        linkExamFragment.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                trainQuizNum.setText(String.valueOf(position + 1));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void isCollect(boolean isCollect) {
        collected = isCollect;
        if (isCollect) {
            imageviewCollect.setImageResource(R.mipmap.collected);
        } else {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.test_btn_test_list: {
                if (fragments.isEmpty()) {
                    //去掉，改为弹出
                    DeviceUtil.MyToast(TrainActivity.this, "当前无错题");//
                    break;
                }
                testListAdapter.notifyDataSetChanged();
                popupWindow.showAtLocation(linkExamFragment, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.btn_hide: {
                popupWindow.dismiss();
                break;
            }
            case R.id.train_check_detail: {
                if (fragments.isEmpty()) {
                    DeviceUtil.MyToast(TrainActivity.this, "当前无错题");
                    break;
                }
                if (fragments.size() > 0) {
                    fragments.get(linkExamFragment.getCurrentItem()).showDetail();
                }
                break;
            }
            case R.id.train_collect: {
                if (fragments.isEmpty()) {
                    DeviceUtil.MyToast(TrainActivity.this, "当前无错题");
                    break;
                }
                if (userid != null && !userid.isEmpty()) {
                    String isright;
                    if (list.containsKey(linkExamFragment.getCurrentItem())) {
                        isright = (list.get(linkExamFragment.getCurrentItem())) ? "1" : "0";
                    } else {
                        isright = "2";
                    }

                    String choose;
                    if (trainChoose.containsKey(linkExamFragment.getCurrentItem())) {
                        choose = String.valueOf(trainChoose.get(linkExamFragment.getCurrentItem()));
                    } else {
                        choose = "0";
                    }
                    int positions = linkExamFragment.getCurrentItem();
                    String isright1 = fragments.get(positions).isRight() ? "1" : "0";
                    if (collected) {
                        presenter.collectRemove(libId, userid, "2", fragments.get(positions).getTid(), fragments.get(positions).getTtype());
                    } else {
                        presenter.testCollect(fragments.get(positions).getTId(), fragments.get(positions).getTtype(), libId, userid, isright1, fragments.get(positions).getResult());
                    }
                    break;
                } else {
                    Intent intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.TRAIN_TO_LOGIN);
                    startActivity(intent);
                }
            }
            case R.id.prev_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (linkExamFragment.getCurrentItem() != 0) {
                            linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() - 1);
                        } else {

                        }
                    }
                });
                break;
            }
            case R.id.next_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        if (pos==1) {
//                            fragments.get(0).initSelectsResult();
//
//                        }
                        trainQuizNum.setText(String.valueOf(position + 1));


                    }
                });
                break;
            }
        }
    }

    public void addQuizCorrect(int position, boolean isCurrent) {

        list.put(position, isCurrent);
        if (!isCurrent) {
            wrong = wrong + 1;
            examPopupWrong.setText(String.valueOf(wrong));
            answerWrong++;
        } else {
            right = right + 1;
            examPopupRight.setText(String.valueOf(right));
        }

        examPopupMiss.setText(String.valueOf(total - wrong - right));
    }

    public void addQuizChoose(int position, int choose) {
        trainChoose.put(position, choose);
    }

    public void onEventMainThread(TrainRandomStartBean bean) {
        if (bean.getReturn_code() == 0) {
            total = bean.getTotal();
            trainId.put(linkExamFragment.getCurrentItem(), bean.getData().getId());
            trainTtype.put(linkExamFragment.getCurrentItem(), bean.getData().getTtype());
            for (int i = 0; i < (bean.getTotal()); i++) {
                TrainFragment trainFragment = new TrainFragment(i, trainType, userid, libId, total);
                fragments.add(trainFragment);
            }

            trainQuizNum.setText("1");
            trainQuizCount.setText(" " + bean.getTotal());
            adapter.notifyDataSetChanged();
            testListAdapter.setSize(bean.getTotal());
            testListAdapter.notifyDataSetChanged();
            examPopupMiss.setText(String.valueOf(total));
        } else if (bean.getReturn_code() == -206) {
            if (trainType == 1) {
                presenter.trainRandomStart("1", libId, userid, "1");
            }
        } else if (bean.getReturn_code() == -205) {
            linearLayoutEmpty.setVisibility(View.VISIBLE);
            linkExamFragment.setVisibility(View.GONE);
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
            hideLoading();
            finish();
        }
        hideLoading();
    }

    public void onEventMainThread(CollectRemoveBean bean) {
        if (bean.getReturn_code() == 0) {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
            collected = false;
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    /**
     * 判断用户是不是做完了所有的题目
     *
     * @return true 做完了, false 没做完
     */
    public boolean isAllAnswer() {
        return list.size() == total;
    }

    public void onEventMainThread(TestCollectBean bean) {
        if (bean.getReturn_code() == 0) {
            isCollect(true);
        }
        DeviceUtil.MyToast(this, bean.getMsg());
        hideLoading();
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    public void selectRightAnswer(final int page) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                linkExamFragment.setCurrentItem(page);
            }
        });
    }
}
